package ua.kharkov.knure.pereverziev.diploma.web.command.ajax;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import ua.kharkov.knure.pereverziev.diploma.db.DAOServices.ServiceFactory;
import ua.kharkov.knure.pereverziev.diploma.db.entity.User;
import ua.kharkov.knure.pereverziev.diploma.web.command.Command;

public class AjaxUserChange implements Command {

	private static final Logger log = Logger.getLogger(AjaxUserChange.class);

	@Override
	public String execute(final HttpServletRequest request,
			final HttpServletResponse response) throws IOException,
			ServletException {

		final String userId = request.getParameter("user_id");
		log.debug("Request parameter: userId --> " + userId);

		final String id = request.getParameter("id");
		log.debug("Request parameter: id --> " + id);

		String value = request.getParameter("value");
		log.debug("Request parameter: value --> " + value);

		if (userId == null || id == null || value == null)
			return "<script>window.location.reload();</script>";
		final User user = ServiceFactory.getInstance().getUserService()
				.get(Long.parseLong(userId));
		if (user == null)
			return "Error. Value Was not changed.";

		if ("email".equals(id)) {
			user.setEmail(value);
			log.debug("Email changed");
		} else if ("password".equals(id)) {
			user.setPassword(value);
			value = "******************".substring(0, value.length());
			log.debug("Password changed");
		} else if ("name".equals(id)) {
			user.setName(value);
			log.debug("Name changed");
		} else if ("surname".equals(id)) {
			user.setSurname(value);
			log.debug("Surname changed");
		}

		request.getSession().setAttribute("user", user);
		ServiceFactory.getInstance().getUserService().merge(user);
		return value;
	}
}
